package com.shcz.migu.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.shcz.migu.ui.base.BaseActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 工具类，app启动时需要调用init方法实现初始化，保存ApplicationContext，创建缓存路径
 *
 * @author levin
 */
@SuppressLint({"SimpleDateFormat", "DefaultLocale"})
public class CommonUtils {

    public static String CACHE_ROOT;
    public static String EMoneyFund_ROOT;
    public static final String CACHE_FUND_FILES_PATH = "fund_files/";
    public static final String CACHE_HTTP_DATA_PATH = "data/";
    public static final String CACHE_IMAGE_PATH = "images/";
    public static final String CACHE_INFOR_COLLECT_PATH = "infors/";

    private static final boolean isDebug = false;

    private static Context mContext;
    private static boolean isAppActive = false;

    public static void init(Context context) {
        mContext = context;
        isAppActive = true;
        createAppCacheDir();
    }


    /**
     * 系统安全退出
     */
    public static void exit(Activity ct) {
        //清除通知
        android.os.Process.killProcess(android.os.Process.myPid());
        ct.onBackPressed();
    }

    public static Context getAppContext() {
        return mContext;
    }

    /**
     * 是否为空
     *
     * @param value
     * @return
     */
    public static boolean isEmpty(String value) {
        if (value == null || value.length() == 0) {
            return true;
        }
        return false;
    }

    private static void createAppCacheDir() {
        String caString = CommonUtils.getSdCardDir(mContext);
        if (caString == null) {
            caString = mContext.getFilesDir().getAbsolutePath().toString();
        }

        String dir = "/wakaka/";

        String cache = caString + dir;//mContext.getString(MResource.getResourceIdByName(mContext.getPackageName(), "string", "app_name")); /*mContext.getPackageName()  "/PETKIT_MATE/"*/;

        CACHE_ROOT = cache + "cache/";
        EMoneyFund_ROOT = cache;
        File file = new File(cache);
        if (!file.isDirectory()) {
            file.delete();
        }
        if (!file.exists()) {
            file.mkdirs();
        }

        file = new File(CACHE_ROOT);
        if (!file.isDirectory()) {
            file.delete();
        }
        if (!file.exists()) {
            file.mkdirs();
        }


        file = new File(CACHE_ROOT + CACHE_HTTP_DATA_PATH);
        if (!file.isDirectory()) {
            file.delete();
        }
        if (!file.exists()) {
            file.mkdirs();
        }

        file = new File(EMoneyFund_ROOT + CACHE_FUND_FILES_PATH);
        if (!file.isDirectory()) {
            file.delete();
        }
        if (!file.exists()) {
            file.mkdirs();
        }

        file = new File(CACHE_ROOT + CACHE_IMAGE_PATH);
        if (!file.isDirectory()) {
            file.delete();
        }
        if (!file.exists()) {
            file.mkdirs();
        }

        file = new File(CACHE_ROOT + CACHE_INFOR_COLLECT_PATH);
        if (!file.isDirectory()) {
            file.delete();
        }
        if (!file.exists()) {
            file.mkdirs();
        }

    }

    public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {// 处理目录
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {// 如果是文件，删除
                        file.delete();
                    } else {// 目录
                        if (file.listFiles().length == 0) {// 目录下没有文件或者目录，删除
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /*
    生成一个新的文件路径
     */
    public static String getNewPath(String path) {
        String newPath = FileOperation.getPathPng();
        File oldFile = new File(path);
        File newFile = new File(newPath);
        newFile = oldFile;
        if (newFile == null)
            return null;
        return newPath;
    }

    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }
    }

    /**
     * 获取缓存目录
     *
     * @return
     */
    public static String getAppCacheDirPath() {
        File file = new File(CACHE_ROOT);
        if (!file.exists())
            file.mkdirs();
        return CACHE_ROOT;
    }

    /**
     * 获取数据目录
     *
     * @return
     */
    public static String getAppDirPath() {
        File file = new File(EMoneyFund_ROOT);
        if (!file.exists())
            file.mkdirs();
        return EMoneyFund_ROOT;
    }


    /**
     * 获取fund文件目录
     *
     * @return
     */
    public static String getFundFilesDirPath() {
        File file = new File(getAppDirPath() + CACHE_FUND_FILES_PATH);
        if (!file.exists())
            file.mkdirs();
        return getAppDirPath() + CACHE_FUND_FILES_PATH;
    }

    /**
     * 获取联网数据缓存目录 CACHE_HTTP_DATA_PATH
     *
     * @return
     */
    public static String getAppCacheHttpDataDirPath() {
        File file = new File(getAppCacheDirPath() + CACHE_HTTP_DATA_PATH);
        if (!file.exists())
            file.mkdirs();
        return getAppCacheDirPath() + CACHE_HTTP_DATA_PATH;
    }

    /**
     * 获取图片缓存目录 CACHE_IMAGE_PATH
     *
     * @return
     */
    public static String getAppCacheImageDirPath() {
        File file = new File(getAppCacheDirPath() + CACHE_IMAGE_PATH);
        if (!file.exists())
            file.mkdirs();
        return getAppCacheDirPath() + CACHE_IMAGE_PATH;
    }

    /**
     * 获取信息采集缓存目录 CACHE_INFOR_COLLECT_PATH
     *
     * @return
     */
    public static String getAppCacheInforCollectDirPath() {
        File file = new File(getAppCacheDirPath() + CACHE_INFOR_COLLECT_PATH);
        if (!file.exists())
            file.mkdirs();
        return getAppCacheDirPath() + CACHE_INFOR_COLLECT_PATH;
    }

    /**
     * 获取根据屏幕获取实际大小
     * 在自定义控件中，根据屏幕的大小来获取实际的大小
     * <p>
     * 例如：orgSize为10，
     * <p>
     * 如果在density为160的屏幕，返回值为10
     * 如果在屏幕为240的屏幕上返回15
     * 如果在屏幕为320的屏幕上返回20
     *
     * @param ctx
     * @param orgSize dip
     * @return 返回相应的px
     */
    public static int getActualSize(Context ctx, int orgSize) {
        WindowManager windowManager = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        float density = (float) displayMetrics.density;
        return (int) (orgSize * density);
    }

    public static float getActualSize(Context ctx, float orgSize) {
        WindowManager windowManager = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        float density = (float) displayMetrics.density;
        return (orgSize / density);
    }


    /**
     * 得到系统级别的缓存对象
     *
     * @param context
     * @return
     */
    public static SharedPreferences getSysShare(Context context) {
        if (context != null)
            return context.getSharedPreferences(Constants.APP_CACHE_PATH, Context.MODE_PRIVATE);
        return null;
    }

    public static double getWidthPixelsProportion(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        float density = (float) displayMetrics.density;
        int widthPixels = displayMetrics.widthPixels;
        int heightPixels = displayMetrics.heightPixels;
        Logger.i("屏幕密度 :" + density + "宽 :" + widthPixels + "高 :" + heightPixels);
        return (double) 1440 / (double) widthPixels;
    }

    /**
     * 添加系统缓存信息
     *
     * @param key
     * @param value
     */
    public static void addSysMap(String key, String value) {
        Editor sysEdit = getSysShare(mContext).edit();
        sysEdit.putString(key, value);
        sysEdit.commit();
    }


    /**
     * 添加系统缓存信息
     *
     * @param context
     * @param key
     * @param value
     */
    public static void addSysMap(Context context, String key, String value) {
        Editor sysEdit = getSysShare(context).edit();
        sysEdit.putString(key, value);
        sysEdit.commit();
    }

    public static void addSysSet(Context context, String key, Set<String> value) {
        Editor sysEdit = getSysShare(context).edit();
        sysEdit.putStringSet(key, value);
        sysEdit.commit();
    }

    /**
     * 得到系统缓存
     *
     * @param key
     * @return
     */
    public static String getSysMap(String key) {
        return getSysMap(mContext, key, "");
    }


    /**
     * 得到系统缓存
     *
     * @param context
     * @param key
     * @return
     */
    public static String getSysMap(Context context, String key) {
        return getSysMap(context, key, "");
    }

    public static void addSysIntMap(Context context, String key, int value) {
        Editor sysEdit = getSysShare(context).edit();
        sysEdit.putInt(key, value);
        sysEdit.commit();
    }

    public static void addSysBoolMap(Context context, String key, boolean value) {
        Editor sysEdit = getSysShare(context).edit();
        sysEdit.putBoolean(key, value);
        sysEdit.commit();
    }

    public static int getSysIntMap(Context context, String key) {
        return getSysIntMap(context, key, 0);
    }

    public static int getSysIntMap(Context context, String key, int defaultValue) {
        SharedPreferences share = getSysShare(context);
        if (share != null) {
            return share.getInt(key, defaultValue);
        }
        return 0;
    }

    /**
     * 得到系统缓存
     *
     * @param context
     * @param key
     * @param defValue
     * @return
     */
    public static String getSysMap(Context context, String key, String defValue) {
        SharedPreferences share = getSysShare(context);
        if (share != null) {
            return share.getString(key, defValue);
        }
        return defValue;
    }

    /**
     * 得到系统缓存
     *
     * @param context
     * @param key
     * @return
     */
    public static Set<String> getSysSet(Context context, String key) {
        SharedPreferences share = getSysShare(context);
        if (share != null) {
            return share.getStringSet(key, new LinkedHashSet<String>());
        }
        return new LinkedHashSet<String>();
    }


    /**
     * 删除系统缓存信息
     *
     * @param context
     * @param key
     * @return
     */
    public static boolean removeSysMap(Context context, String key) {
        SharedPreferences share = getSysShare(context);
        if (share != null) {
            Editor sysEdit = getSysShare(context).edit();
            sysEdit.remove(key);
            sysEdit.commit();
            return true;
        }
        return false;
    }

    /**
     * 添加boolean型系统缓存
     *
     * @param context
     * @param key
     * @param defaultValue
     * @return
     */
    public static boolean getSysBoolMap(Context context, String key, boolean defaultValue) {
        SharedPreferences share = getSysShare(context);
        boolean bool = share.getBoolean(key, defaultValue);
        return bool;
    }

    /**
     * 退出的时候清除通知
     */
    public static void clearNotify(Context mContext) {
        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(0);
    }


    /**
     * 返回当前程序版本名
     */
    public static int getAppVersionCode(Context context) {
        int versioncode = 0;
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versioncode = pi.versionCode;

        } catch (Exception e) {
            LogUtil.e("VersionInfo", "Exception");
        }
        return versioncode;
    }

    /**
     * 返回当前程序版本号
     */
    public static String getAppVersionName(Context context) {
        String versionName = null;
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;

        } catch (Exception e) {
            LogUtil.e("VersionInfo", "Exception");
        }
        return versionName;
    }

    /**
     * 获取GridView的高度
     *
     * @param gridView
     * @param numColumns
     * @return
     */
    public static int getGridViewHeight(GridView gridView, int numColumns, int space) {
        ListAdapter listAdapter = gridView.getAdapter();
        if (listAdapter == null) {
            return 0;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i += numColumns) {
            View listItem = listAdapter.getView(i, null, gridView);
            if (listItem != null) {
                listItem.measure(0, 0);
                totalHeight += (listItem.getMeasuredHeight() + space);
            }
        }

        return totalHeight;
    }

    /**
     * 手机号码校验
     *
     * @param phoneNumber
     * @return
     */
    public static boolean checkPhoneNumber(String phoneNumber) {
        if (isEmpty(phoneNumber)) return false;
        return phoneNumber.matches("^((\\+86)|(86))?(13|14|15|17|18)\\d{9}$");
    }

    /**
     * @param emailStr
     * @return 判断email格式是否正确
     */
    public static boolean checkEmail(String emailStr) {
        boolean ret = false;
        if (!isEmpty(emailStr)) {
            ret = emailStr.contains("@") && emailStr.contains(".");
        }

        return ret;
    }

    /**
     * 计算日期与当前日期相差的天数
     *
     * @param smdate 较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    @SuppressLint("SimpleDateFormat")
    public static int daysBetweenFutureDay(String smdate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sdf.parse(sdf.format(cal.getTime())));
            long time1 = cal.getTimeInMillis();
            cal.setTime(sdf.parse(smdate));
            long time2 = cal.getTimeInMillis();
            long between_days = (time2 - time1) / (1000 * 3600 * 24);
            return Integer.parseInt(String.valueOf(between_days));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static boolean isSD() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }

    /**
     * 获取sd卡路径
     *
     * @param context
     * @return
     */
    public static String getSdCardDir(Context context) {
        if (!isSD()) {
            return null;
        }
        String sdDir = Environment.getExternalStorageDirectory()
                .getAbsolutePath().toString();
        LogUtil.d("getSdCardDir", "sd dir path = " + sdDir);
        return sdDir;
    }


    /**
     * @return true if the app is debuggable, false otherwise
     */
    public static boolean isDebuggable(Context context) {
        if (context == null) {
            return false;
        }

        if (isDebug) {
            return true;
        }

        ApplicationInfo appInfo = context.getApplicationInfo();
        if (appInfo != null) {
            return ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
        } else {
            return (ApplicationInfo.FLAG_DEBUGGABLE != 0);
        }
    }


    public static String getChatTimeFromString(long time) {
        Date date;
        String timeStr = "";
        try {
            date = new Date(time);
            Date curDate = new Date();
//			int days = daysBetween(curDate, date);
            int days = DateUtil.daysOfTwo(date, curDate);
            if (days == 0) {
                return DateUtil.date2Str(date, DateUtil.DATE_FORMAT_6);
            } else if (days == 1) {
                return "昨天 " + DateUtil.date2Str(date, DateUtil.DATE_FORMAT_6);
            } else if (days < 7) {
                return DateUtil.date2Str(date, DateUtil.DATE_FORMAT_13);
            } else {
                return DateUtil.date2Str(date, DateUtil.DATE_FORMAT_2);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return timeStr;
    }


    public static String getChatTimeFromString(String time) {
        if (isEmpty(time)) {
            return null;
        }
        SimpleDateFormat format2 = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = format2.parse(time);
            Date curDate = new Date();
            switch (compareTwoDateState(date, curDate)) {
                case 1:
                    return DateUtil.date2Str(date, DateUtil.DATE_FORMAT_6);
                case 2:
                case 3:
                    return DateUtil.date2Str(date, DateUtil.DATE_FORMAT_5);
                case 4:
                    return DateUtil.date2Str(date, DateUtil.DATE_FORMAT_2);
                default:
                    break;
            }
            return format2.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 判断两个日期是否是同一天、同一月、同一年
     *
     * @param dateA
     * @param dateB
     * @return 1： 同一天；2：同一月；3：同一年；4：其他
     */
    public static int compareTwoDateState(Date dateA, Date dateB) {
        Calendar calDateA = Calendar.getInstance();
        calDateA.setTime(dateA);

        Calendar calDateB = Calendar.getInstance();
        calDateB.setTime(dateB);

        if (calDateA.get(Calendar.YEAR) == calDateB.get(Calendar.YEAR)) {
            if (calDateA.get(Calendar.MONTH) == calDateB.get(Calendar.MONTH)) {
                if (calDateA.get(Calendar.DAY_OF_MONTH) == calDateB.get(Calendar.DAY_OF_MONTH)) {
                    return 1;
                }
                return 2;
            }
            return 3;
        }
        return 4;
    }


    /**
     * 判断两个日期是否是同一天、同一月、同一年
     *
     * @param dateA
     * @param dateB
     * @return 1： 同一天；2：同一月；3：同一年；4：其他
     */
    public static int compareTwoDateState2(Date dateA, Date dateB) {
        Calendar calDateA = Calendar.getInstance();
        calDateA.setTime(dateA);

        Calendar calDateB = Calendar.getInstance();
        calDateB.setTime(dateB);

        if (calDateA.get(Calendar.YEAR) == calDateB.get(Calendar.YEAR)) {
            if (calDateA.get(Calendar.MONTH) == calDateB.get(Calendar.MONTH)) {
                if (calDateA.get(Calendar.DAY_OF_MONTH) == calDateB.get(Calendar.DAY_OF_MONTH)) {
                    return 1;
                }
                return 2;
            }
            return 3;
        }
        return 4;
    }

    /**
     * 获取offset天数以前的日期，格式是yyyyMMdd
     *
     * @param offset
     * @return
     */
    public static String getDateStringByOffset(int offset) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        long cur = new Date().getTime();
        long offsetT = ((long) offset) * 24 * 60 * 60 * 1000;
        long ts = cur - offsetT;
        String date = sdf.format(ts);

        return date;
    }

    /**
     * 获取offset天数以前的日期，格式是MM-dd
     *
     * @param offset
     * @return
     */
    public static String getDateStringByOffset2(int offset, Date curDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        long cur = curDate.getTime();
        long offsetT = ((long) offset) * 24 * 60 * 60 * 1000;
        long ts = cur - offsetT;
        String date = sdf.format(ts);

        return date;
    }

    /**
     * 获取offset月数以前的日期，格式是yyyy-MM
     *
     * @param offset
     * @return
     */
    public static String getDateStringByOffsetMouth(int offset) {
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - offset);

        return sdf.format(cal.getTime());
    }

    /**
     * 获取offset天数以前的日期，格式是MM-dd
     *
     * @param baseDay
     * @param offset
     * @return
     */
    public static String getDateStringByOffset2(int baseDay, int offset) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd");
        long cur;
        try {
            cur = sdf1.parse(String.valueOf(baseDay)).getTime();
            long offsetT = ((long) offset) * 24 * 60 * 60 * 1000;
            long ts = cur - offsetT;

            return sdf2.format(ts);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * 计算两个日期之间相差的天数
     *
     * @param day1 较大的时间
     * @param day2 较小的时间
     * @return 相差天数
     */
    public static int daysBetween(int day1, int day2) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            Date smdate = sdf.parse(String.valueOf(day1));
            Date bdate = sdf.parse(String.valueOf(day2));
            Calendar cal = Calendar.getInstance();
            cal.setTime(smdate);
            long time1 = cal.getTimeInMillis();
            cal.setTime(bdate);
            long time2 = cal.getTimeInMillis();
            long between_days = (time1 - time2) / (1000 * 3600 * 24);
            return Integer.parseInt(String.valueOf(between_days));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }


    /**
     * 计算两个日期之间相差的天数
     *
     * @param day1 较大的时间
     * @param day2 较小的时间
     * @return 相差天数
     */
    public static int daysBetween(Date day1, Date day2) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(day1);
            long time1 = cal.getTimeInMillis();

            cal.setTime(day2);
            long time2 = cal.getTimeInMillis();
            long between_days = (time1 - time2) / (1000 * 3600 * 24);
            return Integer.parseInt(String.valueOf(between_days));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 获取相对某天的偏差值
     *
     * @param day    格式yyyyMMdd
     * @param offset
     * @return
     */
    public static int getDayAfterOffset(int day, int offset) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date;
        try {
            date = sdf.parse(String.valueOf(day));
            long dayTime = date.getTime();
            long offsetT = ((long) offset) * 24 * 60 * 60 * 1000;

            return Integer.valueOf(sdf.format(dayTime + offsetT));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return -1;
    }

    /**
     * 获取两个日期间隔的毫秒数
     *
     * @param time1 yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
     * @param time2 yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
     * @return
     */
    public static long getDaysBetweenMilis(String time1, String time2) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

        try {
            Date date1 = sdf.parse(time1);
            Date date2 = sdf.parse(time2);

            return date1.getTime() - date2.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return 0;
    }


    /**
     * float取一位小数
     *
     * @param value
     * @return
     */
    public static String formatStringValueFromFloat(float value) {
        String result;
        if (value == 0) {
            result = "-";
        } else {
            result = String.format("%.1f", value);
        }

        return result;
    }


    /**
     * 获取color
     *
     * @param cId id
     * @return r
     */
    public static int getColorById(int cId) {
        return mContext.getResources().getColor(cId);
    }

    public static int getPixelById(int dId) {
        return mContext.getResources().getDimensionPixelSize(dId);
    }


    /**
     * 获取当前联网类型
     *
     * @return r
     * Consts.NETWORK_NONE 无网路类型
     * Consts.NETWORK_MOBILE 手机流量
     * Consts.NETWORK_WIFI wifi
     */
    public static int getAPNType() {

        int netType = Constants.NETWORK_NONE;
        ConnectivityManager connMgr = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            LogUtil.d("networkInfo.getExtraInfo()",
                    "networkInfo.getExtraInfo() is "
                            + networkInfo.getExtraInfo());
            netType = Constants.NETWORK_MOBILE;
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = Constants.NETWORK_WIFI;
        }

        return netType;

    }


    /**
     * 设置App是否在前台
     *
     * @param state
     */
    public static void setAppActiveState(boolean state) {
        isAppActive = state;
    }


    public static boolean isRunningForeground() {
//		if(mContext == null){
//			return false;
//		}
//
//		ActivityManager am = (ActivityManager) mContext
//				.getSystemService(Context.ACTIVITY_SERVICE);
//		if(am.getRunningTasks(1).size() > 0){
//			ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
//			String currentPackageName = cn.getPackageName();
//			if (!TextUtils.isEmpty(currentPackageName)
//					&& currentPackageName.equals(mContext.getPackageName())) {
//				return true;
//			}
//		}
        return isTopActivity();
    }

    /**
     * 判断App是否在前台
     *
     * @return
     */
    public static boolean isTopActivity() {
        if (!isAppActive || mContext == null) {
            return false;
        }

//        PackageManager packageManager = mContext.getPackageManager();
//        // getPackageName()是你当前类的包名，0代表是获取版本信息
//        PackageInfo packInfo;
//		try {
//			packInfo = packageManager.getPackageInfo(mContext.getPackageName(),0);
//		} catch (NameNotFoundException e) {
//			return false;
//		}
//        String packageName = packInfo.packageName;
//
//        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
//        List<RunningTaskInfo>  tasksInfo = activityManager.getRunningTasks(1);
//        if(tasksInfo.size() > 0){
//            //应用程序位于堆栈的顶层
//            if(packageName.equals(tasksInfo.get(0).topActivity.getPackageName())){
//                return true;
//            }
//        }
//        return false;

        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) {
            return false;
        }
        for (RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(mContext.getPackageName())) {
                if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }


    public static int getAndroidSDKVersion() {
        return Build.VERSION.SDK_INT;
    }

    /**
     * 获取listview的高度
     *
     * @param listView
     * @return
     */
    public static int getTotalHeightofListView(ListView listView) {
        ListAdapter mAdapter = listView.getAdapter();
        int totalHeight = 0;
        if (mAdapter != null) {
            for (int i = 0; i < mAdapter.getCount(); i++) {
                View mView = mAdapter.getView(i, null, listView);
                mView.measure(
                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                // mView.measure(0, 0);
                totalHeight += mView.getMeasuredHeight();
            }
            totalHeight += (listView.getDividerHeight() * (mAdapter.getCount() - 1));
        }
        return totalHeight;
    }

    /**
     * 判断当前语言是否是中文
     *
     * @param context
     * @return
     */
    public static boolean isSystemLanguateZh(Context context) {
        Locale locale = context.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh"))
            return true;
        else
            return false;
    }

    public static String getSystemLanguage() {
        Locale locale = mContext.getResources().getConfiguration().locale;
        return locale.toString();
    }

    public static void showLongToast(Activity activity, String msg) {
        showToast(activity, msg, 0, Toast.LENGTH_LONG);
    }

    public static void showLongToast(Activity activity, String msg, int iconResId) {
        showToast(activity, msg, iconResId, Toast.LENGTH_LONG);
    }

    public static void showLongToast(Activity activity, int stringId) {
        showToast(activity, activity.getString(stringId), 0, Toast.LENGTH_LONG);
    }

    public static void showLongToast(Activity activity, int stringId, int iconResId) {
        showToast(activity, activity.getString(stringId), iconResId, Toast.LENGTH_LONG);
    }

    public static void showShortToast(Activity activity, String msg) {
        showToast(activity, msg, 0, Toast.LENGTH_SHORT);
    }

    public static void showShortToast(Activity activity, String msg, int iconResId) {
        showToast(activity, msg, iconResId, Toast.LENGTH_SHORT);
    }

    public static void showShortToast(Activity activity, int stringId) {
        showToast(activity, activity.getString(stringId), 0, Toast.LENGTH_SHORT);
    }

    public static void showShortToast(Activity activity, int stringId, int iconResId) {
        showToast(activity, activity.getString(stringId), iconResId, Toast.LENGTH_SHORT);
    }

    public static void showToast(Activity activity, String text, int iconResId, int type) {
        CommonToast.showToast(activity, text, iconResId, type);
    }

    public static boolean hasAtTags(String string) {
        if (!isEmpty(string)) {
            Pattern pattern = Pattern.compile("<a\\s+href=\"([^<>\"]*)\"[^<>]*>(.+?)</a>", Pattern.DOTALL);
            Matcher matcher = pattern.matcher(string);
            while (matcher.find()) {
                return true;
            }
        }

        return false;
    }


    /**
     * @param s 需要检验的字符串
     * @return 字符中含有中文返回true，否则返回false
     */
    public static boolean isContainChinese(String s) {
        boolean result;
        String regex = ".*[\\u4e00-\\u9fa5]+.*";   //匹配含中文字符的任意字符串的正则表达式  .匹配任意单个字符  *匹配前面的子字符串任意次   +匹配前面的子字符串至少一次
        result = s.matches(regex);
        return result;
    }

    /**
     * @return 获取系统状态栏的高度
     */
    public static int getStatusHeight() {
        int statusHeight = 0;
        int resouceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resouceId > 0) statusHeight = mContext.getResources().getDimensionPixelSize(resouceId);
        return statusHeight;
    }

    /**
     * @return 获取系统导航栏高度（虚拟按键的高度）
     */
    public static int getNavigationBarHeight() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return 0;
        if (!checkDeviceHasNavigationBar()) return 0;
        Resources resources = mContext.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height",
                "dimen", "android");
        //获取NavigationBar的高度
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    /**
     * 检测系统是否有导航栏
     *
     * @return true/false
     */
    public static boolean checkDeviceHasNavigationBar() {
        boolean hasNavigationBar = false;
        Resources rs = mContext.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hasNavigationBar;
    }

    public static int getBirthIntFromSring(String s) {
        s = s.replaceAll("-", "");
        return Integer.valueOf(s);
    }


    /**
     * 根据seconds计算小时数
     *
     * @param seconds 秒
     * @return 小时
     */
    public static int convertHourFromSeconds(int seconds) {
        int hour = seconds / 3600;
        int min = (seconds / 60) % 60 + (seconds % 60 >= 30 ? 1 : 0);
        if (min == 60) {
            hour++;
        }
        return hour;
    }

    /**
     * 根据seconds计算小时数
     *
     * @param seconds 秒
     * @return 小时
     */
    public static int convertMinFromSeconds(int seconds) {
        return (seconds / 60) % 60 + (seconds % 60 >= 30 ? 1 : 0);
    }


    /**
     * 监听键盘高度
     *
     * @param activity activity
     * @param listener listener
     */
    public static void observeSoftKeyboard(Activity activity, final OnSoftKeyboardChangeListener listener) {
        final View decorView = activity.getWindow().getDecorView();
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            int previousKeyboardHeight = -1;

            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);
                int displayHeight = rect.bottom - rect.top;
                int height = decorView.getHeight();
                int keyboardHeight = height - displayHeight;
                if (previousKeyboardHeight != keyboardHeight) {
                    boolean hide = (double) displayHeight / height > 0.8;
                    listener.onSoftKeyBoardChange(keyboardHeight, !hide);
                }

                previousKeyboardHeight = height;

            }
        });
    }

    public interface OnSoftKeyboardChangeListener {
        void onSoftKeyBoardChange(int softKeybardHeight, boolean visible);
    }


    /**
     * ListView已到底部的判断
     *
     * @param listView
     * @return
     */
    public static boolean isListViewReachBottomEdge(final ListView listView) {
        boolean result = false;
        if (listView.getLastVisiblePosition() == (listView.getCount() - 1)) {
            final View bottomChildView = listView.getChildAt(listView.getLastVisiblePosition() - listView.getFirstVisiblePosition());
            if (bottomChildView != null) {
                result = (listView.getHeight() >= bottomChildView.getBottom());
            }
        }
        ;
        return result;
    }

    /**
     * 10进制转16进制
     */
    public static String IntToHex(int n) {
        char[] ch = new char[20];
        int nIndex = 0;
        while (true) {
            int m = n / 16;
            int k = n % 16;
            if (k == 15)
                ch[nIndex] = 'F';
            else if (k == 14)
                ch[nIndex] = 'E';
            else if (k == 13)
                ch[nIndex] = 'D';
            else if (k == 12)
                ch[nIndex] = 'C';
            else if (k == 11)
                ch[nIndex] = 'B';
            else if (k == 10)
                ch[nIndex] = 'A';
            else
                ch[nIndex] = (char) ('0' + k);
            nIndex++;
            if (m == 0)
                break;
            n = m;
        }
        StringBuffer sb = new StringBuffer();
        sb.append(ch, 0, nIndex);
        sb.reverse();
        String strHex = new String("0x");
        strHex += sb.toString();
        return strHex;
    }


    /**
     * 16进制转10进制
     */
    public static int HexToInt(String strHex) {
        int nResult = 0;
        if (!IsHex(strHex))
            return nResult;
        String str = strHex.toUpperCase();
        if (str.length() > 2) {
            if (str.charAt(0) == '0' && str.charAt(1) == 'X') {
                str = str.substring(2);
            }
        }
        int nLen = str.length();
        for (int i = 0; i < nLen; ++i) {
            char ch = str.charAt(nLen - i - 1);
            try {
                nResult += (GetHex(ch) * GetPower(16, i));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return nResult;
    }

    //计算16进制对应的数值
    public static int GetHex(char ch) throws Exception {
        if (ch >= '0' && ch <= '9')
            return (int) (ch - '0');
        if (ch >= 'a' && ch <= 'f')
            return (int) (ch - 'a' + 10);
        if (ch >= 'A' && ch <= 'F')
            return (int) (ch - 'A' + 10);
        throw new Exception("error param");
    }

    //计算幂
    public static int GetPower(int nValue, int nCount) throws Exception {
        if (nCount < 0)
            throw new Exception("nCount can't small than 1!");
        if (nCount == 0)
            return 1;
        int nSum = 1;
        for (int i = 0; i < nCount; ++i) {
            nSum = nSum * nValue;
        }
        return nSum;
    }

    //判断是否是16进制数
    public static boolean IsHex(String strHex) {
        int i = 0;
        if (strHex.length() > 2) {
            if (strHex.charAt(0) == '0' && (strHex.charAt(1) == 'X' || strHex.charAt(1) == 'x')) {
                i = 2;
            }
        }
        for (; i < strHex.length(); ++i) {
            char ch = strHex.charAt(i);
            if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))
                continue;
            return false;
        }
        return true;
    }


    /**
     * Convert byte[] to hex string.这里我们可以将byte转换成int，然后利用Integer.toHexString(int)
     * 来转换成16进制字符串。
     *
     * @param src byte[] data
     * @return hex string
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv + " ");
        }
        return stringBuilder.toString();
    }

    public static Integer getScreenWidth(BaseActivity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    public static Integer getScreenHeight(BaseActivity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

}
